import { Body, Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { AuthDto } from './dto';
import * as argon from 'argon2';
import { PrismaClientKnownRequestError } from '@prisma/client/runtime';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class AuthService {
  constructor(
    private prismaService: PrismaService,
    private jwt: JwtService,
    private config: ConfigService,
  ) {}

  async login(@Body() dto: AuthDto) {
    const res = await this.prismaService.user.findUnique({
      where: {
        name: dto.name,
      },
    });
    const success = await argon.verify(res.password, dto.password);
    if (success === true) {
      return { access_token: await this.signToken(dto.name) };
    } else {
      return 'false';
    }
  }

  async register(@Body() dto: AuthDto) {
    try {
      const hash = await argon.hash(dto.password);
      return this.prismaService.user.create({
        data: {
          name: dto.name,
          password: hash,
          email: '954535216@qq.com',
        },
        select: {
          email: true,
          id: true,
          name: true,
        },
      });
    } catch (err) {
      if (err instanceof PrismaClientKnownRequestError) {
        if (err.code === 'P2002') {
          throw new Error('用户名已经被注册');
        } else {
          throw new Error();
        }
      }
    }
  }

  async signToken(username: string): Promise<string> {
    const data = {
      sub: username,
    };
    return this.jwt.signAsync(data, {
      expiresIn: '15m',
      secret: this.config.get('jwt_password'),
    });
  }
}
